﻿using System;
using Storyteller.Framework.Math;

namespace Storyteller.Framework.Graphics.Particles.Emitters
{
	public class RectangleEmitter : ParticleEmitter
	{
		public bool Edge { get; set; }

		public float Width { get { return 2 * halfWidth; } set { halfWidth = value / 2; } }
		public float Height { get { return 2 * halfHeight; } set { halfHeight = value / 2; } }

		float halfWidth;
		float halfHeight;

		public RectangleEmitter(int maximumParticles, int particlesPerSecond, Texture texture)
			: base(maximumParticles, particlesPerSecond, texture)
		{
			Width = Height = 1;
		}

		public RectangleEmitter(int maximumParticles, int particlesPerSecond, Texture texture, TextureRegion textureRegion)
			: base(maximumParticles, particlesPerSecond, texture, textureRegion)
		{
			Width = Height = 1;
		}

		protected override void EmitParticles(int count, Particle[] destination, int offset)
		{
			Vector2 position = WorldPosition + LocalPosition;
			float rotation = WorldRotation + LocalRotation;

			for (int i = 0; i < count; i++)
			{
				Particle p = destination[offset + i];

				Matrix4 transform = Matrix4.CreateRotationZ(rotation) * Matrix4.CreateTranslation(position.X, position.Y, 0);

				if (Edge)
				{
					bool onSide = random.NextBool();

					if (onSide)
					{
						bool onLeft = random.NextBool();
						if (onLeft)
							p.Position.X = -halfWidth;
						else
							p.Position.X = halfWidth;
						p.Position.Y = random.NextFloat(-halfHeight, halfHeight);
					}
					else
					{
						p.Position.X = random.NextFloat(-halfWidth, halfWidth);
						bool onTop = random.NextBool();
						if (onTop)
							p.Position.Y = -halfHeight;
						else
							p.Position.Y = halfHeight;
					}
				}
				else
				{
					p.Position.X = random.NextFloat(-halfWidth, halfWidth);
					p.Position.Y = random.NextFloat(-halfHeight, halfHeight);
				}

				p.Position = Vector2.Transform(p.Position, transform);

				p.Velocity = random.NextUnitVector2() * InitialSpeed;
				p.Lifetime = 0;
				p.Scale = InitialScale;
				p.Rotation = InitialRotation;
				p.Color = InitialColor;
			}
		}
	}
}
